


function Window() {
    this.size = 3;
    this.animation_speed = "slow";
}

Window.prototype.addWeek = function(new_week) {

    var monday_date = new_week.attr('id');
    var insertAfter = null;
    var offset = null;
    // return false to break the each loop
    $('div.week').not('#weekTemplate').each(function(){
        if (monday_date < this.id) {
            insertAfter = $(this);
            offset += $(this).outerHeight();
        }
        if (monday_date >= this.id) {
            return false;
        }
    });

    if (insertAfter !== null) {
        new_week.insertAfter(insertAfter).css("top", offset);
    } else {
        new_week.prependTo('div#timesheet');
    }
    var height = new_week.outerHeight(true);
    new_week.nextAll().animate({"top": "+=" + new_week.outerHeight(true) + "px"}, Window.animation_speed);
    new_week.slideDown();
}

Window.prototype.removeWeek = function() {
    // todo
}

Window.prototype.scrollUp = function() {
    alert('Scrolling up');
}

Window.prototype.scrollDown = function() {

    // disable the scroll button
    $('#scrollDown').attr('disabled', true);

    // scroll the currently displayed weeks
    var animation_height = $('#timesheet .week').eq(0).height();  // height includes margin?
    $('#timesheet .week').eq(0).animate({"top": "-=" + animation_height + "px"}, Window.animation_speed, undefined, function(){
        // delete the top week
        $('#timesheet .week').eq(0).remove();

        // re-enable the scroll button
        $('#scrollDown').attr('disabled', false);
    });
    $('#timesheet .week').animate({"top": "-=" + animation_height + "px"}, Window.animation_speed);

    // add the new (older) week - TODO need to retrieve from the database!
    var last_week_pieces = $('#timesheet .week').eq(2).attr('id').split('-');
    var last_week = new Date(last_week_pieces[0], last_week_pieces[1] - 1, last_week_pieces[2]);
    last_week.setDate(last_week.getDate() - 7);
    this.createWeek($('#timesheet_id').val(), last_week.getFullYear() + '-' + this.zeroPad((last_week.getMonth()+1).toString(),2) + '-' + this.zeroPad(last_week.getDate().toString(),2));

    // slide across the new week
    var timesheets = $('#timesheet .week');
    timesheets.eq(timesheets.length - 1).animate({"left": "-=1000px"}, Window.animation_speed);
}

Window.prototype.realign = function() {
    var offset = 0;
    $(".visible").each(function(){
        offset += $(this).outerHeight();
        $(this).next().animate({"top": offset + "px"}, Window.animation_speed);
    });
}

Window.prototype.show = function() {
    var count = 0;
    var offset = 0;
    $(".week").each(function(){
        count++;
        if (count > Window.size) {
            return false;
        }
        $(this).addClass("visible");
    });
    this.realign();
    $(".visible").show();
}
